#include "lexer.h"
vector<InstructionParseEntry> InstructionParseList;
void append(string &str, InstructionParseEntry &tmp, int &flag)
{
    if (flag == 0)
    {
        flag = 1;
        tmp.instruction = str;
    }
    else
    {
        tmp.operands.push_back(str);
    }
    str = "";
}
ERROR lexAnalysis(string sourceFileName, string lexedFileName)
{

    ifstream inputFile(sourceFileName);
    ofstream outputFile(lexedFileName, ios::trunc);

    // 文件打开失败
    if (!inputFile.is_open() || !outputFile.is_open())
    {
        return OPENING_ERROR;
    }

    // 一个个读取字符 进行单词识别
    string str;
    while (getline(inputFile, str))
    {
        InstructionParseEntry tmp;
        tmp.instruction = "";
        tmp.operands.clear();
        tmp.number = 0;
        int length = str.length();
        tmp.instruction = "";
        string tmpstr = "";
        int flag = 0;
        for (int i = 0; i < length; i++)
        {
            if (str[i] == ' ' || str[i] == '\n')
            {
                if (tmpstr == "")
                    continue;
                append(tmpstr, tmp, flag);
            }
            else if (str[i] == ',')
            {
                append(tmpstr, tmp, flag);
            }
            else if (str[i] == ';')
            {
                append(tmpstr, tmp, flag);
                break;
            }
            else if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
            {
                tmpstr += str[i];
            }
            else
            {
                return ILLEGAL_CHARACTER;
            }
        }
        append(tmpstr, tmp, flag);
        tmp.number = tmp.operands.size();
        if (tmp.number != 0)
        {
            if (!instructionTable.count(tmp.instruction))
                return INSTRUCTION_NO_FIND;
            else if (tmp.number != instructionTable.at(tmp.instruction).nums)
            {
                return INSTRUCTION_NUMS_ERROR;
            }
        }
        InstructionParseList.push_back(tmp);
    }

    // close the input file and output file
    inputFile.close();
    outputFile.close();

    // 返回正确 flag
    return NO_ERROR;
}
